package com.danhuang.cloud.danhuangcore.handler;


import cn.hutool.core.util.StrUtil;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

@Slf4j
@RestControllerAdvice
@Configuration
public class ValidatedExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DhRes validateException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            return DhRes.fail(ResConstant.PARAM_ERROR_CODE,
                    StrUtil.format(ResConstant.map.get(ResConstant.PARAM_ERROR_CODE),
                            fieldErrors.get(0).getField(),
                            fieldErrors.get(0).getDefaultMessage()));
        }

        return DhRes.success();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public DhRes validateException(ConstraintViolationException exception){

        return DhRes.fail(ResConstant.PARAM_ERROR_CODE, exception.getMessage());
    }
}
